package com.sto.stoapp.db.manager;

import com.sto.stoapp.db.StoDataBase;
import com.sto.stoapp.db.constant.ErrorRecordConstant;
import com.sto.stoapp.http.response.upload.ErrorRecordInfo;
import com.sto.stoapp.log.ExceptionLog;
import com.sto.stoapp.util.DateUtil;
import com.sto.stoapp.util.UnifiedStaticType;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;

public class ErrorRecordManager extends StoDataBase implements
		DownLoadDao<ErrorRecordInfo> {
	static ErrorRecordManager mgr;

	static String QUERY_ALL_BY_OPCODE_SITE_CODE = "select * from "
			+ ErrorRecordConstant.ERROR_RECORD_TABLE + " where "
			+ ErrorRecordConstant.RESP_OP_CODE + "=? and "
			+ ErrorRecordConstant.SITE_CODE + "=? order by "
			+ ErrorRecordConstant.TIME + " asc";

	private ErrorRecordManager(Context context) {
		super(context);

	}

	public static ErrorRecordManager getInstance(Context c) {
		if (mgr == null)
			mgr = new ErrorRecordManager(c);
		return mgr;
	}

	public int querySizeByUuid(String uuid) {
		int size = 0;
		SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.READ_DATABASE);
		Cursor cursor = db.rawQuery("select count(*) from "
				+ ErrorRecordConstant.ERROR_RECORD_TABLE + " where "
				+ ErrorRecordConstant.RESP_PDA_UUID + "=?",
				new String[] { uuid });
		if (cursor != null && cursor.moveToFirst()) {
			size = cursor.getInt(0);
		}
		closeCursor(cursor);
		closeDb(UnifiedStaticType.READ_DATABASE);
		return size;

	}

	public List<ErrorRecordInfo> queryByOpCode(String opCode, String siteCode) {
		SQLiteDatabase qb = getSqliteDatabase(UnifiedStaticType.READ_DATABASE);
		Cursor cursor = qb.rawQuery(QUERY_ALL_BY_OPCODE_SITE_CODE,
				new String[] { opCode, siteCode });
		List<ErrorRecordInfo> infos = new ArrayList<ErrorRecordInfo>();
		if (cursor != null && cursor.moveToFirst()) {
			do {
				ErrorRecordInfo info = new ErrorRecordInfo();
				info.respErrorCode = cursor.getString(cursor
						.getColumnIndex(ErrorRecordConstant.RESP_ERROR_CODE));

				info.respErrorDescription = cursor
						.getString(cursor
								.getColumnIndex(ErrorRecordConstant.RESP_ERROR_DESCRIPTION));

				info.respOpCode = cursor.getString(cursor
						.getColumnIndex(ErrorRecordConstant.RESP_OP_CODE));

				info.respPdaUuid = cursor.getString(cursor
						.getColumnIndex(ErrorRecordConstant.RESP_PDA_UUID));

				info.respWaybillNo = cursor.getString(cursor
						.getColumnIndex(ErrorRecordConstant.RESP_WAY_BILL_NO));

				infos.add(info);
			} while (cursor.moveToNext());

		}

		closeCursor(cursor);
		closeDb(UnifiedStaticType.READ_DATABASE);
		return infos;
	}

	@Override
	public void insertOrReplace(List<ErrorRecordInfo> datas) {

		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
			try {
				db.beginTransaction();
				for (ErrorRecordInfo info : datas) {
					ContentValues values = buildContentValues(info);
					if (replace(values)) {
						Log.d("插入一条上传错误", "成功");
					} else {
						Log.d("插入一条上传错误", "失败");
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("insertList", e.getMessage());
			} finally {
				datas.clear();
				db.setTransactionSuccessful();
				db.endTransaction();
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
		}
	}

	public void insertOrReplace(List<ErrorRecordInfo> datas, String siteCode) {

		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
			try {
				db.beginTransaction();
				for (ErrorRecordInfo info : datas) {
					ContentValues values = buildContentValues(info, siteCode);
					if (replace(values)) {
						Log.d("插入一条上传错误", "成功");
					} else {
						Log.d("插入一条上传错误", "失败");
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("insertList", e.getMessage());
			} finally {
				datas.clear();
				db.setTransactionSuccessful();
				db.endTransaction();
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}
		}
	}

	public void deleteOldData() {

		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			try {
				getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE).delete(
						ErrorRecordConstant.ERROR_RECORD_TABLE,
						ErrorRecordConstant.TIME + " <=?",
						new String[] { DateUtil.getYestdayDateTime() });
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("deleteOldData", e.getMessage());
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}

		}

	}

	@Override
	public void deleteAll() {

		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			try {
				getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE).delete(
						ErrorRecordConstant.ERROR_RECORD_TABLE, null, null);
			} catch (Exception e) {
				e.printStackTrace();
				ExceptionLog.writeLog("deleteAll", e.getMessage());
			} finally {
				closeDb(UnifiedStaticType.WRITE_DATABASE);
			}

		}

	}

	@Override
	public boolean replace(ContentValues values) {
		synchronized (UnifiedStaticType.DATABASE_SYNCHRONIZED) {
			long result = 0;
			try {
				SQLiteDatabase db = getSqliteDatabase(UnifiedStaticType.WRITE_DATABASE);
				result = db.replace(ErrorRecordConstant.ERROR_RECORD_TABLE,
						null, values);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result > 0;
		}
	}

	@Override
	public void deleteDataByStatus(String status) {

	}

	@Override
	public String getMaxVersion() {
		return null;
	}

	public ContentValues buildContentValues(ErrorRecordInfo entity,
			String siteCode) {
		ContentValues values = new ContentValues();
		values.put(ErrorRecordConstant.RESP_ERROR_CODE, entity.respErrorCode);
		values.put(ErrorRecordConstant.RESP_ERROR_DESCRIPTION,
				entity.respErrorDescription);
		values.put(ErrorRecordConstant.RESP_OP_CODE, entity.respOpCode);
		values.put(ErrorRecordConstant.RESP_PDA_UUID, entity.respPdaUuid);
		values.put(ErrorRecordConstant.RESP_WAY_BILL_NO, entity.respWaybillNo);
		values.put(ErrorRecordConstant.TIME, DateUtil.getDateTime());
		values.put(ErrorRecordConstant.SITE_CODE, siteCode);
		return values;
	}

	@Override
	public ContentValues buildContentValues(ErrorRecordInfo entity) {
		ContentValues values = new ContentValues();
		values.put(ErrorRecordConstant.RESP_ERROR_CODE, entity.respErrorCode);
		values.put(ErrorRecordConstant.RESP_ERROR_DESCRIPTION,
				entity.respErrorDescription);
		values.put(ErrorRecordConstant.RESP_OP_CODE, entity.respOpCode);
		values.put(ErrorRecordConstant.RESP_PDA_UUID, entity.respPdaUuid);
		values.put(ErrorRecordConstant.RESP_WAY_BILL_NO, entity.respWaybillNo);
		values.put(ErrorRecordConstant.TIME, DateUtil.getDateTime());
		return values;
	}

}
